<!--
 * @Company      : 云集数字科技（山东）股份有限公司
 * @Author       : Lem clownpro@163.com
-->
<template>
  <div class="manager-container">
    <div class="manager-box">
      <div class="manager-config">
        <div class="form-title">配置</div>
        <a-form ref="configFormRef" :model="configForm" :label-col="{ style: { width: '60px' } }" :colon="false" label-align="left">
          <a-form-item label="标题" name="init_name" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
            <a-textarea v-model:value="configForm.init_name" placeholder="请输入标题标题" />
          </a-form-item>
          <a-form-item label="金额" name="init_money" :rules="[{ required: true, message: '请输入金额', trigger: ['blur', 'change'] }]">
            <a-input-group compact>
              <a-input-number v-model:value="configForm.init_money" placeholder="金额" style="width: 130px" :min="0" :step="10000" :precision="2" />
              <a-form-item name="init_money_unit">
                <a-select v-model:value="configForm.init_money_unit" :options="UNIT_LIST" style="width: 90px" />
              </a-form-item>
            </a-input-group>
          </a-form-item>
          <a-form-item label=" ">
            <a-button :loading="configFormLoading" type="primary" @click="configSubmit">初始化</a-button>
          </a-form-item>
        </a-form>
      </div>

      <div class="manager-form">
        <div class="form-title">扣减</div>
        <a-form ref="recordFormRef" :model="recordForm" :label-col="{ style: { width: '85px' } }" :colon="false" label-align="left">
          <a-form-item label="客户名称" name="record_client" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
            <a-input v-model:value="recordForm.record_client" placeholder="请输入客户名称" />
          </a-form-item>
          <a-form-item label="扣减金额" name="record_money" :rules="[{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }]">
            <a-input-number v-model:value="recordForm.record_money" placeholder="请输入扣减金额" style="width: 100%" addon-after="元" :min="0" :step="10000" :precision="2" />
            <a-space wrap style="margin-top: 10px">
              <a-tag v-for="item in standardPrice" :key="item.value" @click="recordForm.record_money = item.value" style="cursor: pointer;">{{ item.label }}</a-tag>
            </a-space>
          </a-form-item>
          <a-form-item label=" ">
            <a-button :loading="recordFormLoading" type="primary" @click="submitRecord">提交</a-button>
          </a-form-item>
        </a-form>
      </div>

      <div class="manager-records">
        <div class="form-title">扣减记录</div>

        <div ref="listRef" class="manager-record-list">
          <div class="manager-record-list-view">
            <div v-for="item in recordList" :key="item.id" class="manager-record-item">
              <span class="manager-record-item-text">{{ item.record_client }}</span>
              <span class="manager-record-item-price">{{ recordMoney(item.record_money) }}</span>
              <span class="manager-record-item-action" @click="recordRemove(item.id)">删除</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { UNIT_LIST, typeFilter } from '@/helper/data';
import { Form as AForm, FormItem as AFormItem, Input as AInput, Textarea as ATextarea, InputGroup as AInputGroup, Select as ASelect, InputNumber as AInputNumber, Button as AButton, FormItemRest as AFormItemRest, Tag as ATag, Space as ASpace, message, Modal } from 'ant-design-vue';
import { onMounted, reactive, ref, toRefs } from 'vue';
import { GetLastConfig, ConfigAdd, RecordAdd, GetRecordList, RecordRemove } from '@/api/config';
import decimal from 'decimal.js'

const configFormRef = ref();
const recordFormRef = ref();
const listRef = ref();

const standardPrice = [
  { label: '1万元', value: 10000 },
  { label: '2万元', value: 20000 },
  { label: '5万元', value: 50000 },
  { label: '10万元', value: 100000 }
]

const state = reactive({
  configForm: {
    id: '',
    init_name: undefined,
    init_money: undefined,
    init_money_unit: 1,
  },
  configFormLoading: false,
  recordFormLoading: false,
  recordForm: {
    config_id: '',
    record_client: undefined,
    record_money: undefined
  },
  recordList: [],
});

const { configForm, recordForm, configFormLoading, recordFormLoading, recordList } = toRefs(state);

onMounted(() => {
  getConfig();
  console.log(listRef.value.scrollTo({
    top: listRef.value.scrollHeight,
    behavior: 'smooth'
  }))
})

async function getConfig() {
  try {
    const res = await GetLastConfig();
    if (res.length > 0) {
      state.configForm = res[0];
      getRecords();
    }
  } catch (e: any) {
    message.error(e.message)
  }
}

async function getRecords() {
  try {
    if (state.configForm.id) {
      const res = await GetRecordList(state.configForm.id);
      state.recordList = res;
    }
  } catch (e: any) {
    message.error(e.message)
  }
}

async function configSubmit() {
  try {
    const values = await configFormRef.value.validate();
    try {
      state.configFormLoading = true;
      await ConfigAdd({
        init_name: values.init_name,
        init_money: values.init_money,
        init_money_unit: values.init_money_unit
      });
      message.success('配置成功');
      getConfig();
    } catch (e: any) {
      message.error(e.message)
    }
    state.configFormLoading = false;
  } catch (e: any) {
    console.log(e)
  }
}

async function submitRecord() {
  try {
    const values = await recordFormRef.value.validate();
    try {
      if (!state.configForm.id) {
        message.error('请先保存配置');
        return;
      }
      // 验证，剩余额度够不够
      let de = decimal(state.configForm.init_money).mul(state.configForm.init_money_unit);
      state.recordList.forEach(item => {
        de = de.sub(item.record_money);
      });
      if (de.toNumber() < values.record_money) {
        message.error(`剩余额度不足，本次最高可扣减 ${de.div(state.configForm.init_money_unit).toNumber()}${typeFilter(UNIT_LIST, state.configForm.init_money_unit)}`);
        return;
      }

      state.recordFormLoading = true;

      await RecordAdd({
        record_client: values.record_client,
        record_money: values.record_money,
        config_id: state.configForm.id
      });
      message.success('扣减成功');
      getRecords();
    } catch (e: any) {
      message.error(e.message)
    }
    state.recordFormLoading = false;
  } catch (e: any) {
    console.log(e)
  }
}

function recordMoney(money) {
  return `${decimal(money).div(state.configForm.init_money_unit).toNumber()}${typeFilter(UNIT_LIST, state.configForm.init_money_unit)}`
}

function recordRemove(id) {
    Modal.confirm({
      title: '提示',
      content: '确认删除该数据？',
      onOk: async() => {
        try {
          await RecordRemove(id);
          message.success('已删除');
          getRecords();
        } catch (e: any) {
          message.error(e.message)
        }
      }
    })
}
</script>
<style lang="scss">

.manager-container{
  width: 100%;
  height: 100vh;
  background-color: #f9f9f9;
  display: flex;
  justify-content: center;
  padding-top: 10vh;
  .manager-box{
    width: 40%;
    height: 600px;
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 0 10px rgba(#000, .05);
    display: flex;
    padding: 20px;
    min-width: 1200px;
  }
  .manager-config {
    width: 280px;
    border-right: 1px solid #ddd;
    padding-right: 20px;
  }
  .manager-form{
    flex: 1;
    margin: 0 20px;
  }
  .manager-records {
    width: 300px;
    border-left: 1px solid #ddd;
    padding-left: 20px;
    .manager-record-list{
      height: calc(600px - 70px);
      overflow-y: auto;
      padding-right: 20px;
      margin-right: -20px;
      .manager-record-item{
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding: 12px 0;
        border-bottom: 1px solid #f1f1f1;
        color: #333;
        .manager-record-item-name{
          width: 100px;
        }
        .manager-record-item-price{
          flex: 1;
          text-align: right;
          padding-right: 28px;
        }
        .manager-record-item-action{
          width: 45px;
          color: red;
          text-align: center;
          cursor: pointer;
        }
        &:last-child{
          font-weight: bold;
        }
      }
    }
  }

  .form-title{
    font-size: 26px;
    color: #333;
    font-weight: bold;
    margin-bottom: 40px;
    position: relative;
    padding-left: 20px;
    &:before{
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6px;
      height: 26px;
      background-color: #2961fa;
    }
  }
}
</style>
